﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using OffInvoiceExcelAddIn.FacturaeFiles;
using System.Windows.Forms;

namespace OffInvoiceExcelAddIn
{
    /// <summary>
    /// Clase que controla la busqueda de la plantilla que mejor se ajuste a la factura que se desea importar.
    /// </summary>
    class TemplateController
    {

        #region "Fields"

        /// <summary>
        /// Variable de tipo char[] que contiene los caracteres que se deben elimiar cuando se cogen los valores
        /// de los controles de la plantilla.
        /// </summary>
        char[] x = { '\r', '\a', '\n' };


        /// <summary>
        /// idioma de la aplicacion
        /// </summary>
        private string language;

        /// <summary>
        /// Variable de tipo string con el valor de la variable de entorno
        /// </summary>
        public string EnvironmentVariable = "";

        /// <summary>
        /// Variable de tipo string que contine el valor del directorio de las plantillas
        /// </summary>
        public string TemplatesDirectories = "";
        
        
        #endregion

        #region "Constructors"

        /// <summary>
        /// Constructor
        /// </summary>
        public TemplateController()
        {
            //InvoiceCulture = CultureInfo.InstalledUICulture;
            EnvironmentVariable = System.Environment.GetEnvironmentVariable("APPDATA");
            CultureInfo cInfo = new CultureInfo(Globals.ThisAddIn.Application.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));
            language = cInfo.Name;
            TemplatesDirectories = string.Concat(language, @"\");
        }

        #endregion

        #region "Public Methods"

        /// <summary>
        /// Método que selecciona la plantilla que mejor se ajusta a un Facturae
        /// </summary>
        /// <param name="facturae">Factura</param>
        /// <param name="corrective">Parémetro que indica si se desea generar una factura rectificativa a partir de otra</param>
        /// <param name="saveOptions">Parámetro que indica si se desean guardar cambios o no</param>
        public void setTemplateType(Facturae facturae, bool corrective, bool saveOptions)
        {
            try
            {
                Language labels = Language.getInstance();
                string invoiceIssuer = facturae.FileHeader.InvoiceIssuerType.ToString("g");
                string invoiceClass = facturae.Invoices[0].InvoiceHeader.InvoiceClass.ToString("g");
                string template = EnvironmentVariable + Paths.TemplatePath + TemplatesDirectories;

                if (invoiceIssuer.ToUpper().Equals("TE"))
                {
                    if (invoiceClass.ToUpper().Equals("OR") || corrective)
                        template += labels.getLabels("CorrectiveAndThirdTemplate")+".xltx";
                    else

                        template += labels.getLabels("ThirdTemplate")+".xltx";
                }
                else
                {
                    if (invoiceClass.ToUpper().Equals("OR") || corrective)
                        template += labels.getLabels("CorrectiveTemplate")+".xltx";
                    else
                        template += labels.getLabels("BasicTemplate")+".xltx";

                }

                object temp = template;
                LoadInvoiceTemplate(temp, saveOptions);

            }
            catch (Exception) { }

        }

        /// <summary>
        /// Método que carga la plantilla
        /// </summary>
        /// <param name="temp">Parámetro de tipo object con la plantilla</param>
        /// <param name="saveOptions">Parámetro de tipo bool que indica si se muestra al usuario la opcion de guardar los cambios o no.</param>
        public void LoadInvoiceTemplate(object temp, bool saveOptions)
        {
            try
            {
                object template = temp;
                object oMissing = System.Reflection.Missing.Value;
                object doNotSaveChanges;

                if (saveOptions)
                {
                    ControlMessages msg = ControlMessages.getInstance();
                    DialogResult dr = MessageBox.Show(msg.getMessage(ControlMessages.Msg.InfoSaveDialog), msg.getMessage(ControlMessages.Msg.CaptionFacturae), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                    if (dr.Equals(DialogResult.Yes))
                    {
                        doNotSaveChanges = true;//Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges;
                    }
                    else
                    {
                        doNotSaveChanges = false;//Microsoft.Office.Interop.Excel.XlSaveAction.xlDoNotSaveChanges;
                        if (dr.Equals(DialogResult.Cancel))
                            throw new Exception();

                    }
                }
                else
                {
                    doNotSaveChanges = false;//Microsoft.Office.Interop.Excel.XlSaveAction.xlDoNotSaveChanges;
                }

                try
                {
                    Globals.ThisAddIn.Application.ActiveWorkbook.Close(doNotSaveChanges, oMissing, oMissing);
                }
                catch (Exception ex)
                {
                }


                Globals.ThisAddIn.Application.Workbooks.Add(template);

            }
            catch (Exception ex) { }
        }


        #endregion
    }
}
